#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_err.h"
#include "cJSON.h"

#include "Datapara.h"
#include "WiFiIno_flash.h"
#include "wifi_apstation.h"
#include "OTA.h"

#define MAX_LENGTH 1000

LocationBatIno_Type_t LocationBatIno;

static const char* TAG = "JSONData";



bool DataPataRunFlag ;
bool TrashInoDataParaFinishFlag;

OTA_Ino_Type_t  AWS_OTA_Ino = {
    .url = "https://example.com",
    .jobId = "jobId",
   .Valid_URL = false,
};

cJSON *uploaddata;


//位置信息、配网信息数据处理
void DataPara(char *RecArrPoint)
{
    char DataPara_RecData_Buff[1024];

    memcpy(DataPara_RecData_Buff, RecArrPoint, 1024);    //注意数组大小的相互匹配

    ESP_LOGI(TAG, "DataPara_RecData_Buff的数据:%s", DataPara_RecData_Buff);
    //char *json_str = {"device_id":"2412000004","building":"{\"id\":66046991,\"name\":\"Main Building\"}","floor":"{\"id\":66047000,\"name\":\"Gaming Floor\"}","room":"{\"id\":66047262,\"name\":\"PIT 4\"}","location":"{\"id\":66237265,\"name\":\"Caesar Rewards Hallway\"}","type":"{\"id\":66237239,\"name\":\"LANDFILL\"}"}
    char *json_str = DataPara_RecData_Buff;
    // 解析整个网页回传的JSON对象
    cJSON *root = cJSON_Parse(json_str);

    if (root!= NULL) {


        // 获取 "ssid" 的值
        cJSON *ssid_json = cJSON_GetObjectItem(root, "ssid");
        if (ssid_json!= NULL && cJSON_IsString(ssid_json)) {
            ESP_LOGI(TAG, "ssid : %s",  ssid_json->valuestring);

            if (ssid_json!= NULL && ssid_json->valuestring!= NULL) {
             strcpy(WiFiIno.ssid, ssid_json->valuestring);
            }
        }
            
        // 获取 "passowrd" 的值
        cJSON *password_json = cJSON_GetObjectItem(root, "password");
        if (password_json!= NULL && cJSON_IsString(password_json)) {
 
            /*数据解析位置高 开启wifi配网信息更新*/
            xEventGroupSetBits(data_analy_event_group, data_analy_start);  //密码传输完毕后将事件组位置高位

             ESP_LOGI(TAG, "password : %s", password_json->valuestring);

             if (password_json!= NULL && password_json->valuestring!= NULL) {
            //  memcpy(WiFiIno.password, password_json->valuestring, strlen(password_json->valuestring));
                strcpy(WiFiIno.password, password_json->valuestring);
            }

             ESP_LOGI(TAG, "WiFiIno.password的数据:%s", WiFiIno.password);
        }


        
        //获取device_id 
        cJSON *device_json = cJSON_GetObjectItem(root, "device_id");
        if (device_json != NULL && cJSON_IsString(device_json)) {

            if(device_json != NULL){
                //   LocationBatIno.device_id = device_json->valuestring;
                 strcpy(LocationBatIno.device_id, device_json->valuestring);
            }
            ESP_LOGI(TAG, "LocationBatIno.device_id设备id : %s", LocationBatIno.device_id);

            int result = sscanf(LocationBatIno.device_id, "%" SCNd64, &LocationBatIno.Dev_id);
            ESP_LOGE(TAG, "LocationBatIno.Dev_id:%" PRId64"", LocationBatIno.Dev_id);
        }
        // cJSON_Delete(device_json);


        // 获取 "building" 的值
        cJSON *building_json = cJSON_GetObjectItem(root, "building");
        if (building_json!= NULL && cJSON_IsString(building_json)) {
            cJSON *building_data = cJSON_Parse(building_json->valuestring);


            if (building_data!= NULL) {
                cJSON *building_id = cJSON_GetObjectItem(building_data, "id");
                cJSON *building_name = cJSON_GetObjectItem(building_data, "name");
                if (building_id!= NULL && cJSON_IsNumber(building_id) && building_name!= NULL && cJSON_IsString(building_name)) {
                    

                    ESP_LOGI(TAG, "Building - ID: %d, Name: %s", building_id->valueint, building_name->valuestring);

                    if (building_id!= NULL && building_id->valueint!= NULL) {
                        LocationBatIno.building_id = building_id->valueint;
                    }

                }
                cJSON_Delete(building_data);
            }
        }

        // 获取 "floor" 的值
        cJSON *floor_json = cJSON_GetObjectItem(root, "floor");
        if (floor_json!= NULL && cJSON_IsString(floor_json)) {
            cJSON *floor_data = cJSON_Parse(floor_json->valuestring);
            if (floor_data!= NULL) {
                cJSON *floor_id = cJSON_GetObjectItem(floor_data, "id");
                cJSON *floor_name = cJSON_GetObjectItem(floor_data, "name");
                if (floor_id!= NULL && cJSON_IsNumber(floor_id) && floor_name!= NULL && cJSON_IsString(floor_name)) {
                    
                    ESP_LOGI(TAG, "Floor - ID: %d, Name: %s", floor_id->valueint, floor_name->valuestring);

                    if (floor_id!= NULL && floor_id->valueint!= NULL) {
                        LocationBatIno.floor_id = floor_id->valueint;
                    }
                }
                cJSON_Delete(floor_data);
            }
        }

        // 获取 "room" 的值
        cJSON *room_json = cJSON_GetObjectItem(root, "room");
        if (room_json!= NULL && cJSON_IsString(room_json)) {
            cJSON *room_data = cJSON_Parse(room_json->valuestring);
            if (room_data!= NULL) {
                cJSON *room_id = cJSON_GetObjectItem(room_data, "id");
                cJSON *room_name = cJSON_GetObjectItem(room_data, "name");
                if (room_id!= NULL && cJSON_IsNumber(room_id) && room_name!= NULL && cJSON_IsString(room_name)) {
                    ESP_LOGI(TAG, "Room - ID: %d, Name: %s", room_id->valueint, room_name->valuestring);

                    if (room_id!= NULL && room_id->valueint!= NULL) {
                        LocationBatIno.room_id = room_id->valueint;
                    }
                }
                cJSON_Delete(room_data);
            }
        }

        // 获取 "location" 的值
        cJSON *location_json = cJSON_GetObjectItem(root, "location");
        if (location_json!= NULL && cJSON_IsString(location_json)) {
            cJSON *location_data = cJSON_Parse(location_json->valuestring);
            if (location_data!= NULL) {
                cJSON *location_id = cJSON_GetObjectItem(location_data, "id");
                cJSON *location_name = cJSON_GetObjectItem(location_data, "name");
                if (location_id!= NULL && cJSON_IsNumber(location_id) && location_name!= NULL && cJSON_IsString(location_name)) {
                    ESP_LOGI(TAG, "Location - ID: %d, Name: %s", location_id->valueint, location_name->valuestring);

                    if (location_id!= NULL && location_id->valueint!= NULL) {
                        LocationBatIno.device_location_id = location_id->valueint;
                    }
                }
                cJSON_Delete(location_data);
            }
        }

        // 获取 "type" 的值
        cJSON *type_json = cJSON_GetObjectItem(root, "type");
        if (type_json!= NULL && cJSON_IsString(type_json)) {
            cJSON *type_data = cJSON_Parse(type_json->valuestring);
            if (type_data!= NULL) {
                cJSON *type_id = cJSON_GetObjectItem(type_data, "id");
                cJSON *type_name = cJSON_GetObjectItem(type_data, "name");
                if (type_id!= NULL && cJSON_IsNumber(type_id) && type_name!= NULL && cJSON_IsString(type_name)) {
                    ESP_LOGI(TAG, "Type - ID: %d, Name: %s", type_id->valueint, type_name->valuestring);

                    if (type_id!= NULL && type_id->valueint!= NULL) {
                       LocationBatIno.device_type_id = type_id->valueint;
                    }
                }
                cJSON_Delete(type_data);
            }
        }

        cJSON_Delete(root);
    }

    while(1)
    {
        /*等待wifi配网信息传过来*/
        xEventGroupWaitBits(data_analy_event_group,
                        data_analy_start,
                        pdFALSE,
                        pdFALSE,
                        portMAX_DELAY);


        memset(&wifi_sta_config.sta.ssid, 0, sizeof(wifi_sta_config.sta.ssid));   //清掉ssid
        memcpy(wifi_sta_config.sta.ssid, WiFiIno.ssid, strlen(WiFiIno.ssid));     //将网页传过来的ssid赋值给wifi_sta_config.sta.ssid
        memset(&wifi_sta_config.sta.password, 0, sizeof(wifi_sta_config.sta.password)); //清掉password
        memcpy(wifi_sta_config.sta.password, WiFiIno.password, strlen(WiFiIno.password));//将网页传过来的password赋值给wifi_sta_config.sta.password
        
        //打开station模式，校验wifi名称和密码
        ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );         //设置工作模式为STA
        ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_sta_config) );   //设置wifi配置
        ESP_ERROR_CHECK(esp_wifi_start() );                         //启动WIFI




        
        /*适当阻塞放置看门狗报错*/
        vTaskDelay(pdMS_TO_TICKS(1000));
    }

}

//对云端下发的job 文件进行数据处理，提取出有用的url以及对应的jobId
void OTA_Job_Data_Deal(char *RecTpoicDataPoint)
{
    char *json_str = RecTpoicDataPoint;
    
    cJSON *root = cJSON_Parse(json_str);
    if (root!= NULL) {
        cJSON *excution_json = cJSON_GetObjectItem(root, "execution");
            if (excution_json!= NULL && cJSON_IsObject(excution_json)) {

            cJSON *jobDocument_json = cJSON_GetObjectItem(excution_json, "jobDocument");

            cJSON *jobId_json = cJSON_GetObjectItem(excution_json, "jobId");
            if (jobId_json!= NULL && cJSON_IsString(jobId_json)) {
                    const char *jobId = jobId_json->valuestring;
                    printf("提取成功jobId: %s\n", jobId);
                    AWS_OTA_Ino.jobId = jobId;
                }
                else{
                    printf("没有找到jobId对象\n");
                }

            if (jobDocument_json!= NULL && cJSON_IsObject(jobDocument_json)) {
                cJSON *action_json = cJSON_GetObjectItem(jobDocument_json, "action");
                if (action_json!= NULL && cJSON_IsString(action_json)) {
                    const char *action = action_json->valuestring;
                    printf("action: %s\n", action);
                }
                cJSON *url_json = cJSON_GetObjectItem(jobDocument_json, "url");
                if (url_json!= NULL && cJSON_IsString(url_json)) {
                    const char *url = url_json->valuestring;
                    
                    AWS_OTA_Ino.url = url;     //将url赋值给AWS_OTA_Ino.url
                    AWS_OTA_Ino.Valid_URL = true;   //设置url有效
                    printf("AWS_OTA_Ino.Valid_URL = true, AWS_OTA_Inourl: %s\n", AWS_OTA_Ino.url);

                    // 启动OTA任务  
                    xTaskCreate(&simple_ota_example_task, "ota_example_task", 8192, NULL, 5, NULL);

                }
                else{
                    printf("没有找到url对象\n");
                }
            }
            else{
                printf("没有找到jobDocument对象\n");
            }
        }  
        else{
            printf("没有找到execution对象\n");
        }  
    } 
}